package com.bms.cfcmms.controller.system;

import com.bms.cfcmms.controller.BaseController;
import com.bms.cfcmms.core.util.Utils;
import com.bms.cfcmms.dao.SystemInfoDao;
import com.bms.cfcmms.model.system.User;
import com.bms.cfcmms.service.LoginService;
import com.bms.cfcmms.util.SpringUtils;
import com.bms.cfcmms.util.annotation.OperationLog;
import com.bms.cfcmms.model.system.SystemInfo;
import com.bms.cfcmms.model.system.authority.Token;
import com.bms.cfcmms.service.UserService;
import com.bms.cfcmms.service.authority.RedisTokenService;
import com.bms.cfcmms.util.ActionResult;
import com.bms.cfcmms.util.Constants;
import com.bms.cfcmms.util.SysUtils;
import com.bms.cfcmms.util.annotation.LoginResult;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by carl on 2016/4/19.
 */
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    public static final String VALIDATECODE = "validateCode";

    @Resource
    protected SystemInfoDao systemInfoDao;
    @Resource
    protected LoginService loginService;
    @Resource
    private RedisTokenService redisTokenService;
    @Resource
    private UserService userService;

    /**
     * 系统登录.
     *
     * @param loginName 用户名
     * @param password  密码
     * @param session   会话
     * @param request   请求
     * @param response  响应
     */
    @RequestMapping(value = "/login.do")
    @OperationLog(description = "login.title")
    @Transactional(propagation = Propagation.REQUIRED)
    public ActionResult login(String loginName,
                              String password, HttpSession session, HttpServletRequest request,
                              HttpServletResponse response){
		//跨域需要(测试)
        String allowAddress = SysUtils.findConstantValue("Access-Control-Allow-Origin");
        response.setHeader("Access-Control-Allow-Origin", allowAddress);
        log.info("methond.begin", "login");
        ActionResult result = new ActionResult();

        SystemInfo systemInfo = systemInfoDao.queryForObjectById(1);
        String number = validateCode(loginName, session, request, response, result, systemInfo);
        if (SpringUtils.hasLength(number)) {
            result.setSuccess(false);
            result.setData(number);
        } else {
            // 登录次数加 1 ,
            session.setAttribute(LoginService.LOGINTIMES, loginService.getLoginTimes(session) + 1);
            Object[] params = {loginName, loginService.getLoginTimes(session)};
            log.debug(SpringUtils.getMessage("login.number", params));

            number = validateUserInfo(loginName, password);
            if (SpringUtils.hasLength(number)) {
                result.setSuccess(false);
                result.setData(number);
            } else {
                Token userNameToken = redisTokenService.createToken();
                result.setData(userNameToken.getUserId());
                result.setSuccess(true);
            }
        }
        return result;
    }

    private String validateCode(String loginName, HttpSession session,
                              HttpServletRequest request, HttpServletResponse response,
                              ActionResult result, SystemInfo systemInfo) {
        // 判断是否要检测验证码
        if (BooleanUtils.isTrue(systemInfo.getAlwaysNeedIdentifingCode())
                || (BooleanUtils.isTrue(systemInfo.getNeedIdentifingCode()
                && loginService.getLoginTimes(session) >= 1))) {
            log.debug(SpringUtils.getMessage("validateCodeisopen", ""));

            // 存在session中的验证码
            String code = ((String) session.getAttribute(VALIDATECODE)).toLowerCase();
            // request 中传入的验证码
            String submitCode = request.getParameter(VALIDATECODE);
            if (!Utils.hasLength(submitCode) || !submitCode.equals(code)) {
                result.setSuccess(false);
                result.setMsg(LoginResult.ERRORIDENTIFYINGCODE.getContext());
                Object[] params = {loginName, LoginResult.ERRORIDENTIFYINGCODE.getContext()};
                log.debug(SpringUtils.getMessage("login.fail", params));
                return Constants.THE_VALIDATECODE_IS_ERROR;
            }
        }
        return null;
    }

    private String validateUserInfo(String loginName, String password) {
        User user = userService.queryForObjectByName(loginName);
        if (user == null) {
            return Constants.THE_USER_OR_PASSORD_IS_NOT_RIGHT;
        }
        if (!user.getPassword().equals(
                userService.genPasswordWithId(user.getUserId(), password))) {
            Object[] params = {loginName, LoginResult.ERRORPASSWORD};
            log.debug(SpringUtils.getMessage("login.user.password.fail", params));
            return Constants.THE_USER_OR_PASSORD_IS_NOT_RIGHT;
        }
        // 帐户被锁定
        if (!user.getAllowLogin()) {
            return Constants.THE_USER_IS_LOCKED;
        }
        return null;
    }
}
